<template>
  <el-card>
    <el-form label-position="top">
      <el-form-item label="告警名称">
        <el-input
          v-model="config.id"
          placeholder="请输入告警名称"
          @change="handleConfigChange"
        />
      </el-form-item>
      <el-form-item label="表名称">
        <el-select
          v-model="config.tableName"
          placeholder="请选择表名称"
          @change="handleConfigChange"
        >
          <el-option
            v-for="name in tableNames"
            :key="name"
            :label="name"
            :value="name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="搜索字段">
        <div class="search-fields-container">
          <SearchFields
            ref="searchFieldsRef"
            :table-name="config.tableName"
            :option-fields="optionFields"
            :existingParams="config.conditionFields"
          />
        </div>
      </el-form-item>

      <el-form-item label="选择数据">
        <el-checkbox-group v-model="config.dataFields">
          <el-checkbox
            v-for="field in optionFields"
            :key="field.name"
            :label="field.name"
          >
            {{ field.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="扫描间隔(秒)">
        <el-input
          v-model.number="config.scanInterval"
          type="number"
          :min="0"
          @change="handleConfigChange"
        />
      </el-form-item>
      <el-form-item label="时间偏移字段">
        <el-select
          v-model="config.offsetIndexField.name"
          placeholder="请选择时间偏移字段"
          clearable
          @change="handleOffsetFieldChange"
        >
          <el-option
            v-for="field in datetimeFields"
            :key="field.name"
            :label="field.label"
            :value="field.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间偏移量(秒)">
        <el-input
          v-model.number="config.offsetIndexField.value"
          type="number"
        />
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import SearchFields from '@/components/SearchFields.vue'
import type { WarningConfig, OptionField, Table } from '@/models/warning'
import { FieldType } from '@/models/warning'
import { chain } from 'lodash'

interface Props {
  tables: Array<Table>
  modelValue: WarningConfig
}

const props = withDefaults(defineProps<Props>(), {
  tables: () => [],
})

const searchFieldsRef = ref(null)
const config = ref<WarningConfig>({
  ...props.modelValue,
  offsetIndexField: props.modelValue.offsetIndexField || {},
  dataFields: props.modelValue.dataFields || [],
})

const tableNames = computed<Array<string>>(() => {
  return props.tables?.map(table => table.name) || []
})

const optionFields = computed<OptionField[]>(() => {
  const result =
    chain(props.tables)
      .filter(table => table.name === config.value.tableName)
      .first()
      .get('fields')
      .map(field => ({
        ...field,
        selected: false,
        alwaysSelected: field.type === 'daterange',
      }))
      .value() || []
  return result
})

const datetimeFields = computed(() => {
  return optionFields.value.filter(
    field => field.field_type === FieldType.DateTime
  )
})

const handleOffsetFieldChange = (fieldName?: string) => {
  if (fieldName) {
    const selectedField = datetimeFields.value.find(f => f.name === fieldName)
    if (selectedField) {
      config.value = {
        ...config.value,
        offsetIndexField: {
          ...selectedField,
          value: config.value.offsetIndexField?.value || 0,
        },
      }
    }
  } else {
    config.value = {
      ...config.value,
      offsetIndexField: {
        ...config.value.offsetIndexField,
      },
    }
  }
}

const handleConfigChange = () => {
  // 配置变更处理
}

// 暴露获取最新配置的方法
const getCurrentConfig = (): WarningConfig => {
  const result = {
    ...config.value,
    conditionFields: searchFieldsRef.value?.generateSearchParams() || [],
    offsetIndexField: {
      ...(config.value.offsetIndexField || {}),
      operator: 'le', // 修改为字符串字面量赋值
    },
  }
  return result
}

defineExpose({
  getCurrentConfig,
})

// 监听props.modelValue变化，更新内部状态
watch(
  () => props.modelValue,
  newVal => {
    config.value = {
      ...newVal,
      offsetIndexField: newVal.offsetIndexField || {},
      dataFields: newVal.dataFields || [],
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.search-fields-container {
  width: 100%;
}
</style>
